package com.three.controller;

import com.three.pojo.ChatMsg;
import com.three.servie.GPT3Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import com.alibaba.fastjson.JSON;

@Component
public class GPT3 implements WebSocketHandler {

    private static final ChatMsg CHAT_MSG = new ChatMsg();

    @Autowired
    private GPT3Service gpt3Service;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("有客户端连接了(GPT-3): " + session.getRemoteAddress().getAddress());
        session.sendMessage(new TextMessage(session.getId()));   // 给用户返回一个WebSocketID 作为用户的唯一标识
        CHAT_MSG.setContent("我是由gyk计算机协会运行的大语言模型，模型名称为qianxiao，模型版本为V1.0。欢迎您使用 GPT 3.0 请文明上网 ");
        session.sendMessage(new TextMessage(JSON.toJSONString(CHAT_MSG)));
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception {
        session.sendMessage(new TextMessage(message.getPayload().toString()));
        ChatMsg msgObj = JSON.parseObject(message.getPayload().toString(), ChatMsg.class); // 将 JSON 转换为 Person 对象
        System.out.println("收到消息(GPT-3): " + msgObj.getContent());
        msgObj.setSender("gpt3");
        msgObj.setContent(gpt3Service.getMessageFromGPT(msgObj.getContent()));
        session.sendMessage(new TextMessage(JSON.toJSONString(msgObj)));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 处理传输错误
        System.out.println("处理传输错误");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("有客户端关闭了连接: " + session.getRemoteAddress().getAddress());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
